package com.wcar.vipmanagement.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.wcar.common.entity.UserBalance;
import com.wcar.common.entity.UserBalanceLog;
import com.wcar.common.vo.Result;
import com.wcar.vipmanagement.dao.OrderMapper;
import com.wcar.vipmanagement.dao.UserBalanceDao;
import com.wcar.vipmanagement.dao.UserBalanceLogMapper;
import com.wcar.vipmanagement.utils.HttpClient;
import com.wcar.vipmanagement.vo.ChongzhiVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: weixing-110
 * @description:
 * @author: 张云龙
 * @create: 2024-05-31 19:58
 **/
@Service
public class OrderServerImpl {
	@Autowired
	private StringRedisTemplate template;

	@Resource
	private UserBalanceLogMapper userBalanceLogMapper ;
	@Resource
	private OrderMapper orderMapper;
	@Autowired
	private UserBalanceDao userBalanceDao;

	@Value("${weixin.appid}")
	private String appId;

	@Value("${weixin.mch_id}")
	private String mchId;

	@Value("${weixin.api_key}")
	private String apikey;

	private ChongzhiVo chongzhiVo1=new ChongzhiVo();
	public Result<Map<String, String>> creataNate(ChongzhiVo chongzhiVo) {
		chongzhiVo1=chongzhiVo;
		//
		if (chongzhiVo.getUserId() != null) {
			String s = new String("损失"+chongzhiVo.getRechargeMoney()+"大洋");
			try {
				Map<String, String> params = new HashMap<>();//请求参数
				params.put("appid", appId);
				params.put("mch_id", mchId);
				params.put("nonce_str", WXPayUtil.generateNonceStr());
				params.put("body", s);
				params.put("out_trade_no",  chongzhiVo.getDetailId());
				//params.put("total_fee", new BigDecimal(order.getTotalFee()).multiply(new BigDecimal(100)).longValue() + "");
				params.put("total_fee", new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue() + "");
				params.put("spbill_create_ip", "127.0.0.1");
				params.put("notify_url", "http://localhost:9000/pay/back");
				params.put("trade_type", "NATIVE");
				HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
				client.setHttps(true);//允许http协议
				client.setXmlParam(WXPayUtil.generateSignedXml(params, apikey));//设置请求参数
				//准备发送请求
				client.post();
				//获取请求响应结果
				String content = client.getContent();
				Map<String, String> map = WXPayUtil.xmlToMap(content);
				//代码没问题,但是找不到符合要求的
				if (map.get("result_code").equals("SUCCESS")) {
					System.out.println("chenggong");
					Map<String, String> result = new HashMap<>();
					result.put("codeUrl", map.get("code_url"));
					result.put("price", chongzhiVo.getRechargeMoney()+"");
					result.put("orderNo",  chongzhiVo.getDetailId());
					return new Result(200, "生成二维码成功", result);
				}
			} catch (Exception e) {

			}


		}
		return new Result(500, "订单失效", null);
	}

	public synchronized Result queryPayStutus(String orderNo) {
		try {
			HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
			HashMap<String, String> params = new HashMap<>();
			params.put("appid", appId);
			params.put("mch_id", mchId);
			params.put("out_trade_no", orderNo);
			params.put("nonce_str", WXPayUtil.generateNonceStr());
			client.setHttps(true);//允许http协议
			client.setXmlParam(WXPayUtil.generateSignedXml(params, apikey));//设置请求参数
			client.post();
			//获取请求响应结果
			String content = client.getContent();
			Map<String, String> map = WXPayUtil.xmlToMap(content);
			//代码没问题,但是找不到符合要求的
			if (map.get("trade_state").equals("SUCCESS")) {
				UserBalanceLog userBalanceLog = new UserBalanceLog();
				userBalanceLog.setUserId(chongzhiVo1.getUserId());
				userBalanceLog.setStoreId(chongzhiVo1.getStoreId());
				//重置金额
				userBalanceLog.setRechargeMoney(chongzhiVo1.getRechargeMoney());
				userBalanceLog.setDiscountsMoney(chongzhiVo1.getDiscountsMoney());
				userBalanceLog.setAccountMoney(chongzhiVo1.getAccountMoney());
				userBalanceLog.setRechargeTime(DateUtil.date());
				int insert = userBalanceLogMapper.insert(userBalanceLog);
				QueryWrapper<UserBalance> objectQueryWrapper = new QueryWrapper<>();
				objectQueryWrapper.eq("store_id",chongzhiVo1.getStoreId());
				objectQueryWrapper.eq("user_id",chongzhiVo1.getUserId());
				UserBalance userBalance = userBalanceDao.selectOne(objectQueryWrapper);

				if (userBalance==null) {
					System.out.println("2222222222222222222222222222222222");
					UserBalance userBalance1 = new UserBalance();
					userBalance1.setStoreId(chongzhiVo1.getStoreId());
					userBalance1.setBalanceTime(DateUtil.date());
					userBalance1.setUserId(chongzhiVo1.getUserId());
					userBalance1.setAmount(BigDecimal.valueOf(chongzhiVo1.getAccountMoney()));
					userBalanceDao.insert(userBalance1);
				}else {
					System.out.println("333333333333333333333333333333");
					BigDecimal amount = userBalance.getAmount();
					BigDecimal bigDecimal = BigDecimal.valueOf(chongzhiVo1.getAccountMoney());
					userBalance.setAmount(amount.add(bigDecimal));
					QueryWrapper<UserBalance> objectQueryWrapper1 = new QueryWrapper<>();
					objectQueryWrapper1.eq("balance_id", userBalance.getBalanceId());
					userBalanceDao.update(userBalance, objectQueryWrapper1);
				}
				return new Result(200,"支付成功",null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new Result(500,"支付失败",null);
	}




}
